<template>
  <div class="container app-container">
    <div class="form">
      <el-form :model="form" :rules="rules" ref="form" label-width="150px">
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          基本信息
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="归属企业" prop="companyId">
              <el-select
                v-model="form.companyId"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.companyNickName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船舶名称" prop="shipName">
              <el-input v-model="form.shipName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船舶类型" prop="shipType">
              <el-select
                v-model="form.shipType"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in shipTypeList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="载货吨位" prop="shipTonLevel">
              <el-input placeholder="请输入" v-model="form.shipTonLevel">
                <template slot="append">吨</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船舶尺寸" prop="shipLength">
              <el-input placeholder="输入长" v-model="form.shipLength" style="margin-top: 10px">
                <template slot="prepend">长</template>
                <template slot="append">m</template>
              </el-input>
              <el-input placeholder="输入宽" v-model="form.shipWidth" style="margin-top: 10px">
                <template slot="prepend">宽</template>
                <template slot="append">m</template>
              </el-input>
              <el-input placeholder="输入高" v-model="form.shipDepth" style="margin-top: 10px">
                <template slot="prepend">高</template>
                <template slot="append">m</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="建造日期" prop="buildDate" required>
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.buildDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="船舶照片" prop="shipPic">
              <div style="width: 800px">
                <image-upload
                  :file-size="fileSize"
                  :file-type="fileType"
                  :limit="limit"
                  :value="form.shipPic"
                  :tip="imgTips"
                  input-type="json"
                  @input="handleUploadImg"
                ></image-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          证件照片
        </div>
        <el-row>
          <el-col :span="6">
            <el-row>
              <el-form-item label="AIS标识码证" prop="aisFile">
                <image-upload
                  :file-size="fileSize"
                  :file-type="fileType"
                  :limit="1"
                  :value="form.aisFile"
                  tip=""
                  @input="handleAisFileImg"
                ></image-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="AIS编码" prop="aisCode">
                <el-input v-model="form.aisCode"></el-input>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-form-item label="船舶国籍证" prop="nationFile">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.nationFile"
                tip=""
                @input="handleNationFileImg"
              ></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-row>
              <el-form-item label="船舶营业运输证(主页)" prop="operatingFile">
                <image-upload
                  :file-size="fileSize"
                  :file-type="fileType"
                  :limit="1"
                  :value="form.operatingFile"
                  tip=""
                  @input="handleOperatingFileImg"
                ></image-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="船舶营业运输证(副页)" prop="operatingFileSubpage">
                <image-upload
                  :file-size="fileSize"
                  :file-type="fileType"
                  :limit="1"
                  :value="form.operatingFileSubpage"
                  tip=""
                  @input="handleOperatingFileSubpageImg"
                ></image-upload>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-row>
              <el-form-item label="船舶安全证书(主页)" prop="safeFile">
                <image-upload
                  :file-size="fileSize"
                  :file-type="fileType"
                  :limit="1"
                  :value="form.safeFile"
                  tip=""
                  @input="handleSafeFileImg"
                ></image-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="船舶安全证书(副页)" prop="safeFileSubpage">
                <image-upload
                  :file-size="fileSize"
                  :file-type="fileType"
                  :limit="1"
                  :value="form.safeFileSubpage"
                  tip=""
                  @input="handleSafeFileSubpageImg"
                ></image-upload>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
        <!--   TODO 下期做再显示     -->
        <el-row hidden="hidden">
          <el-col :span="8">
            <el-form-item label="MMSI码" prop="mmsiCode">
              <el-input v-model="form.mmsiCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船舶适航证" prop="seaworthinessFile">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.seaworthinessFile"
                tip=""
                @input="handleSeaworthinessFileImg"
              ></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="船舶吨位证" prop="tonnageFile">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.tonnageFile"
                tip=""
                @input="handleTonnageFileImg"
              ></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="船舶检验证" prop="inspectionFile">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.inspectionFile"
                tip=""
                @input="handleInspectionFileImg"
              ></image-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="footer">
      <el-button type="primary" class="submit-btn" @click="submitForm">
        {{ isEdit ? '确定保存' : '确定新增' }}
      </el-button>
    </div>
  </div>
</template>

<script>
// 导入接口方法
import { shipTypeEnum, getCompanyList } from '@/api/common';
import { addShip, getShipDetail, updateShip } from '@/api/ship';

export default {
  name: 'SaveShip',
  components: {},
  data() {
    return {
      // 标题
      title: '',
      // 初始化 id 为 null
      id: null,
      // 初始化 isEdit 为 false
      isEdit: false,
      // 表单参数
      form: {
        id: null, // id
        companyId: null, // 所属企业id
        shipName: '', // 船舶名称
        shipType: null, // 船舶类型
        shipTonLevel: 0, // 载货吨位
        shipLength: 0, // 船舶长
        shipWidth: 0, // 船舶宽
        shipDepth: 0, // 船舶高
        buildDate: '', // 建造日期
        shipPic: '', // 船舶照片
        aisFile: '', // AIS标识码证
        nationFile: '', // 船舶国籍证
        operatingFile: '', // 船舶营业运输证(主页)
        operatingFileSubpage: '', //船舶营业运输证(副页)
        safeFile: '', // 船舶安全证书(主页)
        safeFileSubpage: '', // 船舶安全证书(副页)
        aisCode: '', // AIS编码
        mmsiCode: '', // MMIS码
        createType: 1, // 创建类型
        seaworthinessFile: '', //船舶适航证
        tonnageFile: '', //船舶吨位证
        inspectionFile: '', //船舶检验证
      },
      // 图片显示个数
      limit: 10,
      // 图片大小单位M
      fileSize: 5,
      // 图片类型
      fileType: ['jpg', 'jpeg', 'png', 'bmp'],
      // 图片tip
      imgTips: '最多10张，支持 JPG、JPEG、PNG、BMP 格式，大小不超过 5 MB。',
      // 企业列表
      companyList: [],
      // 船舶类型列表
      shipTypeList: [],
      // 表单校验
      rules: {
        companyId: [{ required: true, message: '归属企业不能为空', trigger: 'blur' }],
        shipName: [{ required: true, message: '船舶名称不能为空', trigger: 'blur' }],
        shipType: [{ required: true, message: '船舶类型不能为空', trigger: 'blur' }],
        shipTonLevel: [{ required: true, message: '载货吨位不能为空', trigger: 'blur' }],
        shipLength: [{ required: true, message: '船舶长不能为空', trigger: 'blur' }],
        shipWidth: [{ required: true, message: '船舶宽不能为空', trigger: 'blur' }],
        shipDepth: [{ required: true, message: '船舶高不能为空', trigger: 'blur' }],
        buildDate: [{ required: true, message: '建造日期不能为空', trigger: 'blur' }],
        aisFile: [{ required: true, message: 'AIS标识码证不能为空', trigger: 'blur' }],
        nationFile: [{ required: true, message: '船舶国籍证不能为空', trigger: 'blur' }],
        aisCode: [{ required: true, message: 'AIS编码不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 通过 $route.params 获取路由参数
    this.id = this.$route.query.id ? this.$route.query.id : null;
    // 判断是否存在 id 参数
    this.isEdit = !!this.id;
    if (this.isEdit) {
      this.getDataById(this.id);
    }
  },
  watch: {
    '$route.query.id': {
      handler(newId, oldId) {
        this.id = newId || null;
        this.isEdit = !!newId;
        if (this.isEdit) {
          this.getDataById(this.id);
        }
      },
      immediate: true, // 在组件创建时立刻执行一次
    },
  },
  mounted() {
    this.getShipTypeList();
    this.getCompanyList();
  },
  methods: {
    // 获取船舶类型
    getShipTypeList() {
      shipTypeEnum().then((res) => {
        this.shipTypeList = res.data;
      });
    },

    // 获取企业
    getCompanyList() {
      getCompanyList().then((res) => {
        this.companyList = res.data;
      });
    },

    handleUploadImg(value) {
      this.form.shipPic = value;
    },
    handleAisFileImg(value) {
      this.form.aisFile = value;
    },
    handleNationFileImg(value) {
      this.form.nationFile = value;
    },
    handleOperatingFileImg(value) {
      this.form.operatingFile = value;
    },
    handleOperatingFileSubpageImg(value) {
      this.form.operatingFileSubpage = value;
    },
    handleSafeFileImg(value) {
      this.form.safeFile = value;
    },
    handleSafeFileSubpageImg(value) {
      this.form.safeFileSubpage = value;
    },
    handleSeaworthinessFileImg(value) {
      this.form.seaworthinessFile = value;
    },
    handleTonnageFileImg(value) {
      this.form.tonnageFile = value;
    },
    handleInspectionFileImg(value) {
      this.form.inspectionFile = value;
    },
    /** 获取form表单数据 */
    async getDataById(id) {
      getShipDetail(id).then((res) => {
        this.form = res.data;
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.id != null) {
            this.$confirm('确定修改当前内容', '确定保存', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用修改接口
                this.handleUpdate();
              })
              .catch(() => {});
          } else {
            this.$confirm('确定新增', '确定新增', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用新增接口
                this.handleAdd();
              })
              .catch(() => {});
          }
        }
      });
    },

    /** 新增 */
    handleAdd() {
      let saveData = {
        ...this.form,
      };
      this.$modal.loading('正在保存...');

      addShip(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess('新增成功');
            this.close();
          } else {
            this.$message.error(res.message);
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 更新 */
    handleUpdate() {
      let saveData = {
        ...this.form,
      };
      saveData.id = this.id;
      this.$modal.loading('正在保存...');

      updateShip(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess('保存成功');
            this.close();
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 关闭按钮 */
    close() {
      // 跳转地址 和 携带参数
      const obj = {
        path: '/platform/ship/list/index',
      };
      this.$tab.closeOpenPage(obj).then(() => {
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}

.submit-btn {
  position: fixed;
  bottom: 10px;
  left: 50%;
}
</style>
